package cn.minhx.dtm.demo.service;

import cn.minhx.dtm.starter.core.annotation.DistributedTransaction;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 演示服务类
 *
 * @author min
 */
@Service
public class DemoService implements ApplicationRunner {

	private static final Logger log = LoggerFactory.getLogger(DemoService.class);
	private static final AtomicInteger count = new AtomicInteger(0);

	/** 测试分布式事务注解功能 前两次调用会失败并触发重试，第三次会成功 */
	@DistributedTransaction(interval = 30)
	public void testLocalMessageAspect(int i, String test) {
		int num = count.incrementAndGet();
		log.info("DemoService testLocalMessageAspect count {}", num);
		if (num < 3) {
			throw new RuntimeException("testLocalMessageAspect error");
		}
		log.info("DemoService testLocalMessageAspect i:{}, test:{}", i, test);
	}

	@Override
	@Transactional
	public void run(ApplicationArguments args) throws Exception {
		DemoService proxy = (DemoService) AopContext.currentProxy();
		proxy.testLocalMessageAspect(1, "TEST");
	}
}
